# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date:
# @Last Modified by: CPS
# @Last Modified time: 2021-04-12 03:25:48.660601
# @file_path "D:\CPS\IDE\JS_SublmieText\Data\Packages\CPS"
# @Filename "main.py"
# @Description: 功能描述
#


import sublime
import sublime_plugin
import os
import re
from imp import reload


if int(sublime.version()) < 3176:
    raise ImportWarning("本插件不支持当前版本，请使用大于等于3176的sublime Text")

else:
    from .core.utils import tools

    from .core import settings
    from .core import comments_creator

    # 默认快捷键 ["alt+t"]
    """
    : Description 
    :
    :
    : returns {} returnsDescription
    :
    """
    class TesttTestCommand(sublime_plugin.TextCommand):
        def run(self,edit):
            reload(comments_creator)



    """
    : Description
    :
    :
    : returns {} returnsDescription
    :
    """
    class TesttCommentsCreatorCommand(sublime_plugin.TextCommand):
        """
        : Description Description
        :
        : param  self:{type}  paramDescription
        : param  edit:{type}  paramDescription
        :
        : returns {} {description}
        :
        """
        def run(self,edit):
            view = self.view
            syntax = tools.check_stynax(view.file_name())
            if not syntax or syntax in comments_creator.PARSER:
                parser = comments_creator.PARSER[syntax]()
            else:
                return print('无法解释当前语法')

            options = settings.get_settings().get("comments_creator_optons", False)
            if not options: 
                print('读取配置失败')
                return False

            syntax_tmpl = options['default_tmpl']
            if syntax in options: 
                syntax_tmpl.update(options[syntax])

            # 判断原来是否已有注释块
            begin = syntax_tmpl["preferred_comments_style"][0]
            end = syntax_tmpl["preferred_comments_style"][-1]

            currt_cursor = view.sel()[0].a
            curt_line = view.line(currt_cursor)
            pre_line_search = False # 是否查找了下一行

            search_count = 1
            max_search_count = options.get("max_search_count", 30)
            while search_count <= max_search_count:
                line_str = view.substr(curt_line)
                res = parser.match_line(line_str)
                print('获取当前： ', curt_line)
                print('获取当前： ', line_str)
                if res:
                    # 获取插入的位置(python 装饰器)
                    insert_position = self.get_pre_line_point(curt_line, reg=r'^(\s+)?\@(\w+)$')

                    # 判断原来是否已有注释块
                    old_comments_region = self.get_old_comments(insert_position, begin, end)
                    if old_comments_region:
                        parser.set_old_comments(view.substr(old_comments_region))

                    # 替换或者插入 注释块
                    parser.format_by_tmpl(syntax_tmpl)
                    res = parser.output_str
                    if old_comments_region:
                        view.replace(edit, old_comments_region, res)
                    else:
                        view.insert(edit, insert_position, res)
                    break

                elif not pre_line_search:
                    # 先搜索一次上一行
                    pre_line_search = not pre_line_search
                    curt_line = view.full_line(curt_line.b + 1)
                    search_count = search_count - 1

                else:
                    # 向上查找
                    curt_line = view.full_line(curt_line.a - 1)

                search_count +=1

        """
        : Description 获取原来的注释块数据
        :
        : param  self:{type}             paramDescription
        : param  insert_position:{type}  paramDescription
        : param  comment_begin:{type}    paramDescription
        : param  comment_end:{type}      paramDescription
        :
        : returns {} returnsDescription
        :
        """
        def get_old_comments(self, insert_position, comment_begin, comment_end):
            view = self.view
            begin = comment_begin.strip()
            end = comment_end.strip()

            currt_line = view.line(insert_position)
            line_region = view.full_line(currt_line.a - 1)

            currt_str = view.substr(line_region).strip()
            print('currt_str: ',currt_str, len(currt_str))
            find_end = self.find_line(line_region, end, max_search_count=1)

            if not find_end:
                # print('没有找到end，此处返回', end, len(end))
                return False

            # 向上查找 30行
            search_line = view.full_line(line_region.a - 1)
            find_begin =  self.find_line(search_line, begin, max_search_count=30, direction='up')

            if not find_begin:
                # print('没有找到begin，此处返回', begin,len(begin))
                return False

            old_comment_region = sublime.Region(find_begin.a, find_end.b)

            return old_comment_region

        def insert_result(self, buffer_str, insert_position, syntax_tmpl):
            view = self.view
            begin = syntax_tmpl["preferred_comments_style"][0]
            end =  syntax_tmpl["preferred_comments_style"][-1]
            currt_str = view.line(insert_position).substr().strip()
            pass
            # 判断当前函数是否已拥有注释区

            # 如果没有，则插入新位置

            # 如果有，则使用region 替换注释区

        """
        : Description 查找当前行是否存在reg内容，如果存在，则返回当前行的上一行
        :
        : param  self:{type}       12312
        : param  curt_line:{type}  123123123
        : param  reg:{type}        查找当前行是否存在reg内容，如果存在，则返回当前行的上一行
        :
        : returns {} {description}
        :
        """
        def get_pre_line_point(self, curt_line, reg):
            view = self.view
            prev_line = view.full_line(curt_line.a - 1)
            prev_line_str = view.substr(prev_line)
            reg = re.compile(reg)
            res = reg.findall(prev_line_str)

            if len(res)>0:
                return view.full_line(prev_line.a-1).b
            else:
                return view.full_line(curt_line.a-1).b


        """
        : Description asdfasdfasdf
        :
        : param  self:{type}             在对应的范围内查找某
        : param  line_region:{type}      paramDescription
        : param  find_str:{type}         paramDescription
        : param  max_search_count:{int}  paramDescription
        : param  direction:{string}      查找的方向
        :
        : returns {region}               如果找到，返回当前行的视图对象
        :
        """
        def find_line(self, line_region, find_str, max_search_count=1, direction='up'):
            view = self.view
            search_count = 1
            while search_count <= max_search_count:
                currt_str = view.substr(line_region).strip()
                # print('当前查找： ', currt_str)

                if currt_str.find(find_str) == 0:
                    # 返回当前行尾
                    return line_region
                else:
                    if direction =='up':
                        # 向上查找
                        line_region = view.full_line(line_region.a - 1)
                    else:
                        # 向下查找
                        line_region = view.full_line(line_region.b + 1)

                search_count +=1
            return 0
